<template>
  <view class="service-reviews">
    <!-- 使用系统默认导航栏 -->
    
    <view class="reviews-container">
      <!-- 评价统计 -->
      <ReviewStatistics 
        :rating="reviewStats.rating" 
        :count="reviewStats.count" 
        :good-rate="reviewStats.goodRate" 
      />
      
      <!-- 评价标签 -->
      <ReviewTags 
        :tags="reviewTags" 
        @tag-selected="selectTag" 
      />
      
      <!-- 评价列表 -->
      <view class="reviews-list">
        <view v-if="filteredReviews.length === 0" class="reviews-empty">
          <image class="empty-icon" src="/static/icons/empty.png" mode="aspectFit" />
          <text class="empty-text">暂无相关评价</text>
        </view>
        <ReviewItem 
          v-for="(review, index) in filteredReviews" 
          :key="index" 
          :review="review" 
          @preview-image="previewImage" 
        />
      </view>
      
      <!-- 加载更多 -->
      <LoadMore 
        :loading="loading" 
        :has-more="hasMore" 
        @load-more="loadMoreReviews" 
      />
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { useStore } from 'vuex';
import ReviewStatistics from '../../components/service/ReviewStatistics.vue';
import ReviewTags from '../../components/service/ReviewTags.vue';
import ReviewItem from '../../components/service/ReviewItem.vue';
import LoadMore from '../../components/service/LoadMore.vue';

// 初始化store
const store = useStore();

// 获取传入的服务ID
const options = ref(null);

// 服务ID
const serviceId = ref(0);

// 评分与筛选条件
const activeRating = ref(0); // 0=全部，4=好评，3=中评，1=差评
const hasImage = ref(false);

// 分页状态
const page = ref(1);
const pageSize = ref(10);
const hasMore = ref(true);
const loading = ref(false);

// 从Vuex获取服务评价状态
const currentService = computed(() => store.state.service.currentService);
const reviewList = computed(() => store.state.service.reviews);
const loadingReviews = computed(() => store.state.service.loadingReviews);
const pagination = computed(() => store.state.service.pagination);

// 评价统计
const reviewStats = computed(() => {
  const service = currentService.value;
  if (!service) return { rating: 0, count: 0, goodRate: 0 };
  
  return {
    rating: service.rating || 0,
    count: service.reviewCount || 0,
    goodRate: Math.round((store.getters['service/reviewStats'].good / (store.getters['service/reviewStats'].all || 1)) * 100) || 0
  };
});

// 评价标签
const reviewTags = computed(() => {
  const stats = store.getters['service/reviewStats'];
  return [
    { name: '全部', count: stats.all || 0, active: activeRating.value === 0 && !hasImage.value },
    { name: '好评', count: stats.good || 0, active: activeRating.value === 4 },
    { name: '中评', count: stats.medium || 0, active: activeRating.value === 3 },
    { name: '差评', count: stats.bad || 0, active: activeRating.value === 1 },
    { name: '有图', count: stats.withImages || 0, active: hasImage.value },
    { name: '有回复', count: reviewList.value.filter(r => r.reply).length || 0, active: false }
  ];
});

// 筛选后的评价列表
const filteredReviews = computed(() => {
  if (activeRating.value === 0 && !hasImage.value) {
    return reviewList.value;
  }
  
  let filtered = reviewList.value;
  
  // 按评分筛选
  if (activeRating.value === 4) {
    filtered = filtered.filter(item => item.rating >= 4);
  } else if (activeRating.value === 3) {
    filtered = filtered.filter(item => item.rating === 3);
  } else if (activeRating.value === 1) {
    filtered = filtered.filter(item => item.rating < 3);
  }
  
  // 是否有图片
  if (hasImage.value) {
    filtered = filtered.filter(item => item.images && item.images.length > 0);
  }
  
  return filtered;
});

// 生命周期钩子
onMounted(() => {
  // 获取页面参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  options.value = currentPage.options;
  
  if (options.value && options.value.id) {
    serviceId.value = Number(options.value.id);
    console.log(`加载ID为${serviceId.value}的服务评价`);
    
    // 加载服务详情
    store.dispatch('service/fetchServiceDetail', serviceId.value);
    
    // 加载评价数据
    loadReviews();
  } else {
    uni.showToast({
      title: '参数错误',
      icon: 'none'
    });
  }
});

// 加载评价数据
const loadReviews = async () => {
  if (loading.value) return;
  loading.value = true;
  
  try {
    // 使用Vuex action获取评价数据
    await store.dispatch('service/fetchServiceReviews', {
      serviceId: serviceId.value,
      rating: activeRating.value,
      hasImage: hasImage.value,
      page: page.value,
      pageSize: pageSize.value
    });
    
    // 判断是否还有更多数据
    hasMore.value = reviewList.value.length < pagination.value.total;
    
    // 成功加载数据后页码自增
    if (reviewList.value.length > 0) {
      page.value++;
    }
  } catch (error) {
    console.error('获取评价数据失败', error);
    uni.showToast({
      title: '获取评价数据失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
  }
};

// 加载更多评价
const loadMoreReviews = () => {
  if (loading.value || !hasMore.value) return;
  loadReviews();
};

// 选择标签
const selectTag = (index) => {
  // 重置分页
  page.value = 1;
  hasMore.value = true;
  
  // 根据标签类型设置过滤条件
  if (index === 0) { // 全部
    activeRating.value = 0;
    hasImage.value = false;
  } else if (index === 1) { // 好评
    activeRating.value = 4;
    hasImage.value = false;
  } else if (index === 2) { // 中评
    activeRating.value = 3;
    hasImage.value = false;
  } else if (index === 3) { // 差评
    activeRating.value = 1;
    hasImage.value = false;
  } else if (index === 4) { // 有图
    activeRating.value = 0;
    hasImage.value = true;
  } else if (index === 5) { // 有回复
    activeRating.value = 0;
    hasImage.value = false;
    // 这里仍然需要在前端过滤，因为"有回复"不在SERVICE_RATING枚举中
  }
  
  // 重新加载数据
  loadReviews();
};

// 预览图片
const previewImage = (images, index) => {
  uni.previewImage({
    urls: images,
    current: images[index]
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};
</script>

<style lang="scss" scoped>
  .service-reviews {
    background-color: #f8f8f8;
    min-height: 100vh;
    padding: 12px;
  }
  
  .reviews-container {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .reviews-list {
    border-radius: 12px;
    background-color: #fff;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
    overflow: hidden;
  }

  .reviews-empty {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    padding: 40px 0;
  }

  .empty-icon {
    width: 80px;
    height: 80px;
    margin-bottom: 16px;
    opacity: 0.5;
  }

  .empty-text {
    color: #999;
    font-size: 14px;
  }


  </style>
